package com.itheima.service;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 数据库查找用户名和密码
 */
@Component("securityService")
public class SecurityService implements UserDetailsService {


    @Reference
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        //通过输入的用户名，判断认证
        User user=userService.findUsersAndAuthoritiesByUsername(username);

        if (user==null){
            return null; //认证失败
        }
        Set<Role> roleSet = user.getRoles();
        if (roleSet!=null&&roleSet.size()!=0){
            for (Role role : roleSet) {
                //每一个角色
                SimpleGrantedAuthority sim_role=new SimpleGrantedAuthority(role.getKeyword());
                grantedAuthorities.add(sim_role);
                //每一个角色对应的权限
                Set<Permission> permissions = role.getPermissions();
                if (permissions!=null&&permissions.size()!=0){
                    for (Permission permission : permissions) {
                        SimpleGrantedAuthority sim_per=new SimpleGrantedAuthority(permission.getKeyword());
                        grantedAuthorities.add(sim_per);
                    }

                }

            }
        }


        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),grantedAuthorities);
    }
}
